package com.hxkcloud.patient.dborm;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.table.TableUtils;
import com.hxkcloud.patient.beans.AddressBean;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by william_sun on 2016-07-21.
 * Description:省市区数据库操作类
 */
public class AddressDao {
    private Context context;
    private Dao<AddressBean, Integer> addressDao;

    public AddressDao(Context context) {
        this.context = context;
        try {
            addressDao = DatabaseHelper.getHelper(context).getDao(AddressBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void setAddress(final List<AddressBean> adds) {
        try {
            TransactionManager.callInTransaction(DatabaseHelper.getHelper(context).getConnectionSource(),
                    new Callable<Void>() {
                        @Override
                        public Void call() throws Exception {
                            clearAddress();
                            for (AddressBean add : adds) {
                                addressDao.create(add);
                            }
                            return null;
                        }
                    });

        } catch (SQLException e) {
        }
    }

    public List<AddressBean> getAddress(String pid) {
        try {
            QueryBuilder builder = addressDao.queryBuilder();
            builder.where().eq("parrentId", pid);
            return builder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public AddressBean getOneAddress(String id) {
        try {
            QueryBuilder builder = addressDao.queryBuilder();
            builder.where().eq("itemId", id);
            return (AddressBean) builder.query().get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void clearAddress() {
        try {
            TableUtils.clearTable(addressDao.getConnectionSource(), AddressBean.class);
//            addressDao.queryRaw("delete from addressBean");
//            addressDao.queryRaw("update sqlite_sequence SET seq = 0 where name ='addressBean'");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
